package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    public PageResult<SpuBo> querySpuByPageAndSort(Integer page, Integer rows, Boolean saleable, String key) {
        //分页条件
        PageHelper.startPage(page, rows);
        // 创建查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 是否过滤上下架
        if (saleable != null) {
            criteria.orEqualTo("saleable", saleable);
        }
        // 是否模糊查询
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }
        List<Spu> spus = this.spuMapper.selectByExample(example);

        PageInfo<Spu> pageInfo = new PageInfo<>(spus);
        ArrayList<SpuBo> spuBos = new ArrayList<>();
        spus.forEach(spu->{
            List<String> names = this.categoryService.queryNameByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            // 2、把spu变为 spuBo
            SpuBo spuBo = new SpuBo();
            // 属性拷贝
            BeanUtils.copyProperties(spu, spuBo);
            //把查询到的分类的名称装到spuBos集合
            spuBo.setCname(StringUtils.join(names,"/"));
            //把查询到的品牌的名称装到spuBos集合
            spuBo.setBname(brandMapper.selectByPrimaryKey(spu.getBrandId()).getName());
            spuBos.add(spuBo);
        });
        return new PageResult<>(pageInfo.getTotal(), spuBos);

    }


    //新增商品
    @Transactional
    public void save(SpuBo spuBo) {

        // 分析 spubo里面存有:
        // spu表的全字段（需要手动设置Saleable，Valid，CreateTime,LastUpdateTime），其他字段全映射
        spuBo.setSaleable(true);//上下架状态
        spuBo.setValid(true);//是否有效，0已删除，1有效
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());
        this.spuMapper.insert(spuBo);//直接传过去SpuBo就行了 因为pojo中设置了
        //SpuDetail表里面的全字段（需要手动设置id 是spu表的id ）其他字段全映射
        spuBo.getSpuDetail().setSpuId(spuBo.getId());
        this.spuDetailMapper.insert(spuBo.getSpuDetail());
        saveSkuAndStock(spuBo.getId(), spuBo.getSkus());
        sendMsg(spuBo.getId(),"insert");
    }
    //向队列中发送消息
    private void sendMsg(Long id,String type) {
        try {
            this.amqpTemplate.convertAndSend("item."+type,id);
        } catch (AmqpException e) {
            e.printStackTrace();
        }
    }

    private void saveSkuAndStock(Long spuId, List<Sku> skus) {
        for (Sku sku : skus) {
//            if (!sku.getEnable()) {
//                continue;
//            }                 前端已经过滤了
            //sku表  ======>集合(需要手动设置id是spu表的id,CreateTime,LastUpdateTime)其他字段全映射
            sku.setSpuId(spuId);
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insert(sku);
            //stock表的全字段（需要手动设置id是spu表的id,需要设置库存信息 ）
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            this.stockMapper.insert(stock);
        }
    }

    public SpuDetail querySpuDetailById(Long id) {
        SpuDetail spuDetail = this.spuDetailMapper.selectByPrimaryKey(id);
        return spuDetail;
    }

    public List<Sku> querySkuBySpuId(Long spuId) {
        Sku record = new Sku();
        record.setSpuId(spuId);
        List<Sku> skus = this.skuMapper.select(record);
        // 同时查询出库存
        for (Sku sku : skus) {
            sku.setStock(this.stockMapper.selectByPrimaryKey(sku.getId()).getStock());
        }
        return skus;
    }
    @Transactional
    public void updateGoods(SpuBo spuBo) {
        this.spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());
        // 查询以前sku
       List<Sku> skus=this.skuMapper.querySkuBySpuId(spuBo.getId());
        if (!CollectionUtils.isEmpty(skus)) {
           //拿到skus的所有ids
            List<Long> ids = skus.stream().map(s -> s.getId()).collect(Collectors.toList());
            //删除以前的库存
            Example example = new Example(Stock.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("skuId", ids);
            this.stockMapper.deleteByExample(example);
            //删除以前的sku库存
            Sku record = new Sku();

            record.setSpuId(spuBo.getId());
            this.skuMapper.delete(record);
        }
        // 新增sku和库存
        saveSkuAndStock( spuBo.getId(),spuBo.getSkus());
        //更新spu
        spuBo.setLastUpdateTime(new Date());
        spuBo.setCreateTime(null);
        spuBo.setValid(null);
        spuBo.setSaleable(null);
        this.spuMapper.updateByPrimaryKeySelective(spuBo);
        //向队列发送一条更新消息
        sendMsg(spuBo.getId(),"update");

    }

    public Spu querySpuBySpuId(Long id) {
        return this.spuMapper.selectByPrimaryKey(id);
    }

    public Sku querySkuBySkuId(Long id) {
        Sku sku = this.skuMapper.selectByPrimaryKey(id);
        return sku;
    }
}